#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
文件名称: student_complete_api.py
完整存储路径: backend/api/student_complete_api.py
功能说明:
    学生档案完整管理API
    支持学生档案的查询、完整信息展示等功能
使用说明:
    提供RESTful接口，用于学生档案的完整管理
"""

from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required
from backend.infrastructure.database import db
from backend.models.student import Student
from backend.models.student_extension import StudentExtension
from backend.models.vision import VisionRecord
from backend.models.intervention import InterventionRecord
from backend.models.followup import FollowupRecord
from sqlalchemy import desc
import json
import logging
from backend.config.config_manager import ConfigManager
from backend.services.unified_log_service import UnifiedLogService
from backend.decorators.auth_decorators import (
    require_permissions, require_roles, require_self_or_admin,
    admin_required, teacher_required
)

student_complete_api = Blueprint('student_complete_api', __name__, url_prefix='/api/students/complete')

# 配置管理器和日志服务初始化
def get_config_manager():
    """获取配置管理器实例，避免模块级初始化问题"""
    return ConfigManager()

def get_log_service():
    """获取学生档案日志服务"""
    return UnifiedLogService()

# 🚨 移除开发/生产环境判断，强制配置驱动
# 配置驱动架构要求：所有逻辑必须基于配置，不允许环境判断的兜底机制

# 🔧 配置驱动的数据处理函数（保留 - 这些是业务功能）
def clean_numeric_value(value):
    """
    数值类型清理（完全配置驱动版本）
    """
    if value is None or value == '':
        return None
    
    # 动态获取配置
    config_manager = get_config_manager()
    student_config = config_manager.get_student_archive_config()
    validation_config = student_config.get('data_validation', {})
    clean_rules = validation_config.get('clean_rules', {})
    
    # 字符串去空格处理
    if clean_rules.get('strip_whitespace', True) and isinstance(value, str):
        value = value.strip()
    
    # 空字符串转None
    if clean_rules.get('empty_string_to_none', True) and value == '':
        return None
    
    # 数值转换
    if clean_rules.get('numeric_conversion', True):
        try:
            return float(value)
        except (ValueError, TypeError):
            return None
    
    return value

def clean_boolean_value(value):
    """
    布尔类型清理配置驱动版本
    替代：原硬编码的布尔值处理逻辑
    """
    try:
        if value is None or value == '':
            return False
        
        if isinstance(value, bool):
            return value
        
        if isinstance(value, str):
            true_values = ['true', 'True', '1', 'yes', 'Yes', '是', 'on']
            return value.strip() in true_values
        
        if isinstance(value, (int, float)):
            return bool(value)
        
        return False
        
    except Exception as e:
        logging.error(f"布尔值清理失败: {e}")
        return False

def validate_field_value(field_name, value):
    """
    字段验证（完全配置驱动版本）
    """
    # 动态获取配置
    config_manager = get_config_manager()
    student_config = config_manager.get_student_archive_config()
    basic_fields_config = student_config.get('basic_fields', {})
    extension_fields_config = student_config.get('extension_fields', {})
    
    # 获取字段配置
    field_config = basic_fields_config.get(field_name) or extension_fields_config.get(field_name)
    
    if not field_config:
        return True  # 无配置时默认通过
    
    # 必填字段验证
    if field_config.get('required', False) and (value is None or value == ''):
        return False
    
    # 数值范围验证
    if field_config.get('field_type') == 'number':
        if value is not None:
            min_val = field_config.get('min')
            max_val = field_config.get('max')
            
            if min_val is not None and value < min_val:
                return False
            if max_val is not None and value > max_val:
                return False
    
    # 文本长度验证
    if field_config.get('field_type') in ['text', 'textarea']:
        if value is not None:
            max_length = field_config.get('max_length')
            if max_length and len(str(value)) > max_length:
                return False
    
    # 正则表达式验证
    validation_pattern = field_config.get('validation')
    if validation_pattern and value:
        import re
        if not re.match(validation_pattern, str(value)):
            return False
    
    return True

# 🔧 业务API路由（保留 - 核心业务功能）
@student_complete_api.route('/<int:student_id>/related', methods=['GET'])
@jwt_required()
@require_permissions('student:read')
def get_student_with_related_records(student_id):
    """
    获取学生完整信息，包括基本信息、扩展信息、视力记录、干预记录等
    """
    try:
        # 获取学生基本信息
        student = Student.query.get(student_id)
        if not student:
            return jsonify({"success": False, "error": "学生不存在"}), 404
        
        # 获取学生扩展信息
        extension = StudentExtension.query.filter_by(student_id=student_id).first()
        
        # 获取视力记录（最近10条）
        vision_records = (VisionRecord.query
                         .filter_by(student_id=student_id)
                         .order_by(desc(VisionRecord.measure_date), desc(VisionRecord.measure_time))
                         .limit(10)
                         .all())
        
        # 获取干预记录（最近10条）
        intervention_records = (InterventionRecord.query
                               .filter_by(student_id=student_id)
                               .order_by(desc(InterventionRecord.date), desc(InterventionRecord.operation_time))
                               .limit(10)
                               .all())
        
        # 获取随访记录（最近10条）
        followup_records = (FollowupRecord.query
                           .filter_by(student_id=student_id)
                           .order_by(desc(FollowupRecord.followup_date), desc(FollowupRecord.followup_time))
                           .limit(10)
                           .all())
        
        # 构建返回数据
        result = {
            "success": True,
            "data": {
                "student": student.to_dict(),
                "extension": extension.to_dict() if extension else {},
                "vision_records": [record.to_dict() for record in vision_records],
                "intervention_records": [record.to_dict() for record in intervention_records],
                "followup_records": [record.to_dict() for record in followup_records],
                "vision_count": len(vision_records),
                "intervention_count": len(intervention_records),
                "followup_count": len(followup_records)
            }
        }
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({"success": False, "error": f"服务器错误: {str(e)}"}), 500

@student_complete_api.route('/<int:student_id>', methods=['GET'])
@jwt_required()
@require_permissions('student:read')
def get_student_complete_info(student_id):
    """
    获取学生基本信息和扩展信息（用于编辑表单）
    """
    try:
        student = Student.query.get(student_id)
        if not student:
            return jsonify({"success": False, "error": "学生不存在"}), 404
        
        extension = StudentExtension.query.filter_by(student_id=student_id).first()
        
        # 合并基本信息和扩展信息
        student_data = student.to_dict()
        if extension:
            extension_data = extension.to_dict()
            # 移除可能冲突的字段
            extension_data.pop('id', None)
            extension_data.pop('student_id', None)
            student_data.update(extension_data)
        
        return jsonify({
            "success": True,
            "data": student_data
        })
        
    except Exception as e:
        return jsonify({"success": False, "error": f"服务器错误: {str(e)}"}), 500

@student_complete_api.route('', methods=['POST'])
@jwt_required()
@require_permissions('student:create')
def create_student_complete_info():
    """
    创建新的学生完整信息（完全配置驱动版本）
    """
    try:
        data = request.json
        if not data:
            return jsonify({"success": False, "error": "请求数据不能为空"}), 400
        
        logging.info(f"收到创建学生档案请求，数据: {data}")
        
        # 获取配置管理器
        config_manager = get_config_manager()
        student_config = config_manager.get_student_archive_config()
        basic_fields_config = student_config.get('basic_fields', {})
        extension_fields_config = student_config.get('extension_fields', {})
        
        # 🔧 配置驱动：动态获取必填字段
        required_fields = []
        for field_name, field_config in basic_fields_config.items():
            if field_config.get('required', False):
                required_fields.append(field_name)
        
        # 验证必填字段
        missing_fields = []
        for field in required_fields:
            value = data.get(field)
            if not value or str(value).strip() == '':
                missing_fields.append(field)
        
        if missing_fields:
            return jsonify({
                "success": False, 
                "message": f"以下必填字段不能为空: {', '.join(missing_fields)}",
                "data": None
            }), 400
        
        # 检查教育ID是否已存在
        education_id = data.get('education_id')
        if not education_id:
            return jsonify({"success": False, "error": "教育ID不能为空"}), 400
        
        education_id = education_id.strip()
        existing_student = Student.query.filter_by(education_id=education_id).first()
        if existing_student:
            return jsonify({"success": False, "error": "该教育ID已存在"}), 400
        
        # 🔧 配置驱动：动态处理基本信息字段
        student_data = {}
        for field_name, field_config in basic_fields_config.items():
            if field_name in data:
                value = data[field_name]
                if value and str(value).strip():
                    student_data[field_name] = str(value).strip()
                elif field_config.get('required', False):
                    student_data[field_name] = str(value).strip()
        
        # 创建学生基本信息
        student = Student(**student_data)
        
        # 处理生日字段
        birthday = data.get('birthday')
        if birthday:
            from datetime import datetime
            try:
                student.birthday = datetime.strptime(birthday, '%Y-%m-%d').date()
            except ValueError:
                pass
        
        db.session.add(student)
        db.session.flush()  # 获取student.id
        
        # 🔧 配置驱动：动态处理扩展信息字段
        extension_data = {'student_id': student.id}
        
        # 设置默认数据年份
        extension_data['data_year'] = data.get('data_year', '2024')
        
        for field_name, field_config in extension_fields_config.items():
            if field_name in data and field_name not in ['student_id']:  # 排除关系字段
                value = data[field_name]
                field_type = field_config.get('field_type', 'text')
                
                if field_type == 'number':
                    extension_data[field_name] = clean_numeric_value(value)
                elif field_type == 'checkbox':
                    extension_data[field_name] = clean_boolean_value(value)
                else:
                    extension_data[field_name] = value if value else None
        
        # 创建扩展信息
        extension = StudentExtension(**extension_data)
        db.session.add(extension)
        
        # 🔧 添加统一日志服务
        log_service = get_log_service()
        log_data = {
            'student_id': student.id,
            'education_id': student.education_id,
            'name': student.name,
            'operation_data': student_data,  # 基本信息
            'extension_data': extension_data  # 扩展信息
        }
        
        db.session.commit()
        
        # 记录创建日志
        log_service.log_student_operation(
            student_id=student.id,
            action='CREATE',
            operation_data=log_data,
            operator=data.get('operator', '系统'),
            ip_address=request.remote_addr
        )
        
        return jsonify({
            "success": True,
            "data": {
                "id": student.id,
                "education_id": student.education_id,
                "name": student.name,
                "school": student.school,
                "class_name": student.class_name,
                "grade": extension.grade,
                "gender": student.gender,
                "parent_name": getattr(student, 'parent_name', None)
            },
            "message": "学生信息创建成功"
        })
        
    except Exception as e:
        db.session.rollback()
        import traceback
        error_details = {
            'error_message': str(e),
            'error_type': type(e).__name__,
            'traceback': traceback.format_exc(),
            'request_data': data if 'data' in locals() else 'No data available'
        }
        logging.error(f"创建学生档案失败: {error_details}")
        return jsonify({
            "success": False,
            "message": f"创建失败: {str(e)}",
            "data": None
        }), 500

@student_complete_api.route('/<int:student_id>', methods=['PUT'])
@jwt_required()
@require_permissions('student:edit')
def update_student_complete_info(student_id):
    """
    更新学生完整信息（完全配置驱动版本）
    """
    try:
        data = request.json
        if not data:
            return jsonify({"success": False, "error": "请求数据不能为空"}), 400
        
        # 🔧 添加调试日志
        current_app.logger.info(f"📝 更新学生{student_id}完整信息，接收到的数据: {data}")
        
        # 获取学生记录
        student = Student.query.get(student_id)
        if not student:
            return jsonify({"success": False, "error": "学生不存在"}), 404
        
        # 获取配置管理器
        config_manager = get_config_manager()
        student_config = config_manager.get_student_archive_config()
        basic_fields_config = student_config.get('basic_fields', {})
        extension_fields_config = student_config.get('extension_fields', {})
        
        # 记录原始数据用于日志
        original_student_data = student.to_dict()
        
        # 🔧 配置驱动：动态更新基本信息字段
        updated_basic_fields = []
        for field_name, field_config in basic_fields_config.items():
            if field_name in data:
                old_value = getattr(student, field_name, None)
                new_value = data[field_name]
                
                # 🔧 修复：birthday字段空值处理
                if field_name == 'birthday':
                    if new_value and str(new_value).strip():
                        from datetime import datetime
                        try:
                            new_value = datetime.strptime(new_value, '%Y-%m-%d').date()
                        except ValueError:
                            # 如果日期格式无效，跳过更新此字段
                            continue
                    else:
                        # 如果是空字符串或None，跳过更新，保持原值
                        continue
                
                if old_value != new_value:
                    setattr(student, field_name, new_value)
                    updated_basic_fields.append(field_name)
        
        # 获取或创建扩展信息
        extension = StudentExtension.query.filter_by(student_id=student_id).first()
        if not extension:
            extension = StudentExtension(
                student_id=student_id, 
                data_year=data.get('data_year', '2024')
            )
            db.session.add(extension)
        
        original_extension_data = extension.to_dict()
        
        # 🔧 配置驱动：动态更新扩展信息字段
        updated_extension_fields = []
        current_app.logger.info(f"📝 开始处理扩展字段，extension_fields_config: {list(extension_fields_config.keys())}")
        current_app.logger.info(f"📝 data中的字段: {list(data.keys())}")
        
        for field_name, field_config in extension_fields_config.items():
            if field_name in data and field_name not in ['student_id']:  # 排除关系字段
                old_value = getattr(extension, field_name, None)
                new_value = data[field_name]
                field_type = field_config.get('field_type', 'text')
                
                current_app.logger.info(f"📝 处理字段 {field_name}: old_value={old_value}, new_value={new_value}, field_type={field_type}")
                
                # 🔧 特殊处理：确保data_year不为空
                if field_name == 'data_year' and (new_value is None or new_value == ''):
                    new_value = '2024'  # 设置默认年份
                    current_app.logger.info(f"📝 data_year为空，设置默认值: {new_value}")
                
                # 根据字段类型处理值
                if field_type == 'number':
                    new_value = clean_numeric_value(new_value)
                elif field_type == 'checkbox':
                    new_value = clean_boolean_value(new_value)
                else:
                    new_value = new_value if new_value else None
                
                # 🔧 再次确保data_year不为None
                if field_name == 'data_year' and new_value is None:
                    new_value = '2024'
                
                if old_value != new_value:
                    setattr(extension, field_name, new_value)
                    updated_extension_fields.append(field_name)
                    current_app.logger.info(f"📝 字段 {field_name} 已更新: {old_value} -> {new_value}")
                else:
                    current_app.logger.info(f"📝 字段 {field_name} 无变化: {old_value}")
        
        current_app.logger.info(f"📝 最终要更新的扩展字段: {updated_extension_fields}")
        current_app.logger.info(f"📝 提交前 extension.data_year: {extension.data_year}")
        current_app.logger.info(f"📝 提交前 extension.correction_method: {extension.correction_method}")
        
        # 🔧 添加统一日志服务
        log_service = get_log_service()
        log_data = {
            'student_id': student_id,
            'education_id': student.education_id,
            'name': student.name,
            'updated_basic_fields': updated_basic_fields,
            'updated_extension_fields': updated_extension_fields,
            'original_data': {
                'student': original_student_data,
                'extension': original_extension_data
            },
            'new_data': data
        }
        
        db.session.commit()
        
        # 记录更新日志
        log_service.log_student_operation(
            student_id=student_id,
            action='UPDATE',
            operation_data=log_data,
            operator=data.get('operator', '系统'),
            ip_address=request.remote_addr
        )
        
        return jsonify({
            "success": True,
            "message": "学生信息更新成功",
            "updated_fields": {
                "basic": updated_basic_fields,
                "extension": updated_extension_fields
            }
        })
        
    except Exception as e:
        db.session.rollback()
        logging.error(f"更新学生档案失败: {e}")
        return jsonify({"success": False, "error": f"更新失败: {str(e)}"}), 500

@student_complete_api.route('/get', methods=['GET'])
def get_student_complete():
    """
    获取学生完整档案信息，包括基本信息和扩展信息的所有字段
    """
    try:
        student_id = request.args.get('student_id')
        if not student_id:
            return jsonify({"error": "缺少student_id参数"}), 400

        student = Student.query.get(int(student_id))
        if not student:
            return jsonify({"error": "学生不存在"}), 404

        # 获取学生基本信息
        student_dict = student.to_dict()
        
        # 获取扩展信息
        extension = StudentExtension.query.filter_by(student_id=student.id).first()
        if extension:
            # 合并所有扩展表字段
            ext_dict = extension.to_dict()
            # 移除重复的student_info嵌套，直接合并字段
            if 'student_info' in ext_dict:
                del ext_dict['student_info']
            student_dict.update(ext_dict)

        return jsonify({
            "success": True,
            "student": student_dict
        })
    
    except ValueError:
        return jsonify({"error": "student_id必须为数字"}), 400
    except Exception as e:
        current_app.logger.error(f"获取学生完整档案失败: {e}")
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500

# 🔧 配置接口（完全配置驱动）
@student_complete_api.route('/config', methods=['GET'])
def get_student_config():
    """
    获取学生档案完整配置接口（统一配置源）
    """
    try:
        config_manager = get_config_manager()
        student_config = config_manager.get_student_archive_config()
        
        # 🔧 通过ConfigManager获取全局选项配置（符合三级架构）
        global_options = config_manager.get_global_options()
        
        # 构建完整配置数据
        config_data = {
            'basic_fields': student_config.get('basic_fields', {}),
            'extension_fields': student_config.get('extension_fields', {}),
            'dropdown_options': global_options,  # 使用全局选项池
            'field_groups': student_config.get('field_groups', {}),
            'editing_modes': student_config.get('editing_modes', {}),
            'module_integration': student_config.get('module_integration', {}),
            'data_validation': student_config.get('data_validation', {}),
            'export_config': student_config.get('export_config', {}),
            'yearly_data_management': student_config.get('yearly_data_management', {}),
            'grade_upgrade_rules': student_config.get('grade_upgrade_rules', {}),
            'age_calculation_rules': student_config.get('age_calculation_rules', {})
        }
        
        # 添加配置版本信息
        config_data['_meta'] = {
            'version': '2.0',
            'config_source': 'constants_v2.py',
            'last_updated': '2025-07-12',
            'architecture': 'unified_config_driven'
        }
        
        return jsonify({
            'success': True,
            'data': config_data,
            'message': '学生档案配置获取成功'
        })
        
    except Exception as e:
        logging.error(f"获取学生档案配置失败: {e}")
        import traceback
        logging.error(f"详细错误: {traceback.format_exc()}")
        
        return jsonify({
            'success': False,
            'error': '配置系统故障',
            'message': f'ConfigManager错误: {str(e)}',
            'architecture_note': '这是配置驱动系统的问题，请检查constants_v2.py配置文件'
        }), 500

# 🔧 学生档案日志查询接口
@student_complete_api.route('/<int:student_id>/logs', methods=['GET'])
def get_student_archive_logs(student_id):
    """
    获取指定学生的档案操作日志
    """
    try:
        # 获取查询参数
        limit = request.args.get('limit', 50, type=int)
        action = request.args.get('action')  # 可选的操作类型筛选
        
        # 验证学生是否存在
        student = Student.query.get(student_id)
        if not student:
            return jsonify({"success": False, "error": "学生不存在"}), 404
        
        # 获取日志服务
        log_service = get_log_service()
        result = log_service.get_student_logs(student_id, limit)
        
        if result['success']:
            return jsonify({
                "success": True,
                "student_id": student_id,
                "student_name": student.name,
                "total": result.get('total', 0),
                "logs": result['logs']
            })
        else:
            return jsonify({
                "success": False,
                "error": result.get('error', '获取日志失败')
            }), 500
            
    except Exception as e:
        logging.error(f"获取学生档案日志失败: {e}")
        return jsonify({"success": False, "error": f"服务器错误: {str(e)}"}), 500

@student_complete_api.route('/logs/all', methods=['GET'])
def get_all_student_archive_logs():
    """
    获取所有学生档案操作日志（管理员功能）
    """
    try:
        # 获取查询参数
        limit = request.args.get('limit', 100, type=int)
        action = request.args.get('action')
        operator = request.args.get('operator')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        # 解析日期参数
        from datetime import datetime
        start_date_obj = None
        end_date_obj = None
        
        if start_date:
            try:
                start_date_obj = datetime.strptime(start_date, '%Y-%m-%d')
            except ValueError:
                return jsonify({"success": False, "error": "开始日期格式错误，应为YYYY-MM-DD"}), 400
        
        if end_date:
            try:
                end_date_obj = datetime.strptime(end_date, '%Y-%m-%d')
            except ValueError:
                return jsonify({"success": False, "error": "结束日期格式错误，应为YYYY-MM-DD"}), 400
        
        # 获取日志
        from backend.models.student_archive_log import StudentArchiveLog
        result = StudentArchiveLog.get_all_logs(
            limit=limit,
            action=action,
            operator=operator,
            start_date=start_date_obj,
            end_date=end_date_obj
        )
        
        if result['success']:
            return jsonify({
                "success": True,
                "total": result.get('total', 0),
                "logs": result['logs'],
                "filters": {
                    "action": action,
                    "operator": operator,
                    "start_date": start_date,
                    "end_date": end_date,
                    "limit": limit
                }
            })
        else:
            return jsonify({
                "success": False,
                "error": result.get('error', '获取日志失败')
            }), 500
            
    except Exception as e:
        logging.error(f"获取所有学生档案日志失败: {e}")
        return jsonify({"success": False, "error": f"服务器错误: {str(e)}"}), 500

@student_complete_api.route('/logs/<int:log_id>/restore', methods=['POST'])
def restore_student_from_log(log_id):
    """
    从日志恢复学生档案
    支持两种恢复类型：
    1. 恢复已删除的学生档案
    2. 恢复学生档案到历史版本
    """
    try:
        data = request.get_json() or {}
        operator = data.get('operator', '系统管理员')
        operation_type = data.get('operation_type', '恢复操作')
        
        log_service = get_log_service()
        student_log_service = log_service.get_student_archive_service()
        
        # 获取日志记录
        from backend.models.student_archive_log import StudentArchiveLog
        log = StudentArchiveLog.query.get(log_id)
        if not log:
            return jsonify({
                "success": False,
                "error": "日志记录不存在"
            }), 404
        
        # 根据日志类型执行不同的恢复操作
        action_value = log.action.value if hasattr(log.action, 'value') else str(log.action)
        if action_value == 'DELETE':
            # 恢复已删除的学生档案
            return restore_deleted_student(log, operator, operation_type, student_log_service)
        elif action_value in ['CREATE', 'UPDATE'] and log.old_content:
            # 恢复到历史版本
            return restore_to_historical_version(log, operator, operation_type, student_log_service)
        else:
            return jsonify({
                "success": False,
                "error": "此日志记录不支持恢复操作"
            }), 400
            
    except Exception as e:
        logging.error(f"恢复学生档案失败: {e}")
        return jsonify({
            "success": False,
            "error": f"恢复失败: {str(e)}"
        }), 500

def restore_deleted_student(log, operator, operation_type, student_log_service):
    """恢复已删除的学生档案"""
    try:
        if not log.old_content:
            return jsonify({
                "success": False,
                "error": "删除日志缺少历史数据，无法恢复"
            }), 400
        
        # 解析删除前的学生数据
        import json
        old_data = json.loads(log.old_content)
        
        # 检查学生是否已存在
        existing_student = Student.query.get(log.student_id)
        if existing_student:
            return jsonify({
                "success": False,
                "error": "学生档案已存在，无法恢复删除的记录"
            }), 400
        
        # 重建学生档案
        student = Student()
        for key, value in old_data.get('student', {}).items():
            if hasattr(student, key) and key != 'id':
                setattr(student, key, value)
        
        # 设置原始ID
        if log.student_id:
            student.id = log.student_id
        
        db.session.add(student)
        db.session.flush()  # 获取ID
        
        # 恢复扩展信息
        if old_data.get('extension'):
            extension = StudentExtension()
            for key, value in old_data['extension'].items():
                if hasattr(extension, key) and key not in ['id', 'student_id']:
                    setattr(extension, key, value)
            extension.student_id = student.id
            db.session.add(extension)
        
        db.session.commit()
        
        # 记录恢复操作日志
        student_log_service.log_restore(
            student_id=student.id,
            operator=operator,
            operation_desc=f"{operation_type}：从删除日志恢复学生档案",
            restored_from_log_id=log.id
        )
        
        return jsonify({
            "success": True,
            "message": f"学生档案已成功恢复",
            "student_id": student.id
        })
        
    except Exception as e:
        db.session.rollback()
        logging.error(f"恢复已删除学生档案失败: {e}")
        return jsonify({
            "success": False,
            "error": f"恢复失败: {str(e)}"
        }), 500

def restore_to_historical_version(log, operator, operation_type, student_log_service):
    """恢复学生档案到历史版本"""
    try:
        if not log.old_content:
            return jsonify({
                "success": False,
                "error": "历史日志缺少数据，无法恢复"
            }), 400
        
        # 获取当前学生档案
        student = Student.query.get(log.student_id)
        if not student:
            return jsonify({
                "success": False,
                "error": "学生档案不存在，无法恢复历史版本"
            }), 404
        
        # 解析历史数据
        import json
        old_data = json.loads(log.old_content)
        
        # 备份当前数据用于日志
        current_data = {
            "student": {key: getattr(student, key) for key in dir(student) 
                       if not key.startswith('_') and hasattr(student, key) and 
                       not callable(getattr(student, key)) and key != 'metadata'},
            "extension": {}
        }
        
        extension = StudentExtension.query.filter_by(student_id=student.id).first()
        if extension:
            current_data["extension"] = {key: getattr(extension, key) for key in dir(extension) 
                                       if not key.startswith('_') and hasattr(extension, key) and 
                                       not callable(getattr(extension, key)) and key != 'metadata'}
        
        # 恢复学生基本信息
        for key, value in old_data.get('student', {}).items():
            if hasattr(student, key) and key not in ['id']:
                setattr(student, key, value)
        
        # 恢复扩展信息
        if old_data.get('extension'):
            if not extension:
                extension = StudentExtension(student_id=student.id)
                db.session.add(extension)
            
            for key, value in old_data['extension'].items():
                if hasattr(extension, key) and key not in ['id', 'student_id']:
                    setattr(extension, key, value)
        
        db.session.commit()
        
        # 记录恢复操作日志
        student_log_service.log_restore(
            student_id=student.id,
            operator=operator,
            operation_desc=f"{operation_type}：恢复到历史版本 (日志ID: {log.id})",
            restored_from_log_id=log.id,
            old_content=json.dumps(current_data, ensure_ascii=False, default=str),
            new_content=log.old_content
        )
        
        return jsonify({
            "success": True,
            "message": f"学生档案已恢复到历史版本",
            "student_id": student.id
        })
        
    except Exception as e:
        db.session.rollback()
        logging.error(f"恢复到历史版本失败: {e}")
        return jsonify({
            "success": False,
            "error": f"恢复失败: {str(e)}"
        }), 500

